package db

import (
	"context"
	"fmt"
	"gitee.com/xinshortlink/internal/pkg/conf"
	"log"

	"gitee.com/chunanyong/zorm"
	_ "github.com/go-sql-driver/mysql"
	"go.uber.org/zap"
)

func NewDB(logger *zap.Logger, cc *conf.Conf) *zorm.DBDao {
	dbConf := cc.Database
	c := &zorm.DataSourceConfig{
		DSN:                   fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true&loc=Local", dbConf.Username, dbConf.Password, dbConf.Ip, dbConf.Port, dbConf.DbName),
		DriverName:            "mysql",
		Dialect:               "mysql",
		SlowSQLMillis:         dbConf.SlowSQLMillis,
		MaxOpenConns:          dbConf.MaxOpenConns,
		MaxIdleConns:          dbConf.MaxIdleConns,
		ConnMaxLifetimeSecond: dbConf.ConnMaxLifetimeSecond,
		DefaultTxOptions:      nil,
	}

	db, err := zorm.NewDBDao(c)
	if err != nil {
		log.Panic(err)
	}

	if logger != nil {
		zorm.FuncLogError = func(ctx context.Context, err error) {
			logger.Error("exec sql error", zap.String("err", err.Error()))
		}

		// 记录 panic 日志
		zorm.FuncLogPanic = func(ctx context.Context, err error) {
			logger.Error("exec sql panic", zap.String("err", err.Error()))
		}

		// 记录 SQL 日志。 只有 SlowSQLMillis=0 ，或者 SlowSQLMillis > 0 时，且 SQL 执行时间超过 SlowSQLMillis 时，才会打印日志
		zorm.FuncPrintSQL = func(ctx context.Context, sqlstr string, args []interface{}, execSQLMillis int64) {
			var argsStr = "[]"
			if args != nil {
				argsStr = fmt.Sprintf("%s", args)
			}

			logger.Info("exec sql", zap.String("sql", sqlstr), zap.String("args", argsStr), zap.Int64("execSQLMillis", execSQLMillis))
		}

	}

	return db
}
